package com.java46.service;

import com.java46.bean.Order;
import com.java46.exception.MyException;
import com.java46.mapper.OrderMapper;
import com.java46.util.ServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

// 订单
@Transactional
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 查询所有订单信息
     * @return 返回一个集合
     * @throws MyException
     */
    public List<Order> queryAllOrder() throws MyException {
        List<Order> orders;
        orders = orderMapper.selectAll();
        ServiceUtil.checkListNull(orders,"数据库没有查到订单相关信息");
        return orders;
    }

    /**
     * 根据订单编号查询订单信息
     * @param orderId 订单编号
     * @return
     * @throws MyException
     */
    public Order queryByOrderId(Integer orderId) throws MyException {

        ServiceUtil.checkNull(orderId,"订单编号不能为空！");
        Order order ;
        try {
            order = orderMapper.selectByPrimaryKey(orderId);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据异常！");
        }
        ServiceUtil.checkNull(order,"根据订单编号查询订单信息失败！");

        return order;
    }

    /**
     * 添加订单信息
     * @param order
     * @return
     * @throws MyException
     */
    public Integer addOrder(Order order) throws MyException {

        ServiceUtil.checkNull(order,"订单不能为空！");
        Integer result;
        try {
            result = orderMapper.insert(order);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据异常！");
        }
        ServiceUtil.checkNull(result,"订单信息添加失败！");

        return result;
    }

    /**
     *  根据订单编号删除订单信息
     * @param orderId 订单编号
     * @return
     * @throws MyException
     */
    public Integer deleteOrder(Integer orderId) throws MyException {

        ServiceUtil.checkNull(orderId,"订单编号不能为空！");
        Integer result ;
        try {
            result = orderMapper.deleteByPrimaryKey(orderId);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据异常！");
        }
        ServiceUtil.checkNull(result,"订单信息删除失败！");

        return result;
    }

    /**
     * 修改订单信息
     * @param order
     * @return
     * @throws MyException
     */
    public Integer updateOrder(Order order) throws MyException {

        ServiceUtil.checkNull(order,"订单编号不能为空！");
        Integer result ;
        try {
            result =  orderMapper.updateByPrimaryKey(order);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException("数据异常！");
        }
        ServiceUtil.checkNull(result,"订单信息修改失败！");

        return result;
    }
}
